import React, {
  createContext,
  useContext,
  ReactNode,
  useState,
  useEffect,
} from "react";
import { useQueryState } from "nuqs";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { LangGraphLogoSVG } from "@/components/icons/langgraph";
import { Label } from "@/components/ui/label";
import { ArrowRight } from "lucide-react";
import { PasswordInput } from "@/components/ui/password-input";
import { getApiKey } from "@/lib/api-key";
import { toast } from "sonner";
import { ChatMessage } from "@/lib/types";
import { useAuth } from "@/providers/AuthProvider"; // 添加这个import

// 简化的状态类型，不再依赖LangGraph
export type StateType = { messages: ChatMessage[] };

// 简化的Stream上下文类型
type StreamContextType = {
  messages: ChatMessage[];
  isLoading: boolean;
  error: string | null;
  sendMessage: (content: string) => Promise<void>;
  clearMessages: () => void;
  threadId: string | null;
  setThreadId: (id: string | null) => void;
  submit: (input: any, config?: any) => Promise<void>;
  getMessagesMetadata: (message: any) => any;
  setBranch: (branch: any) => void;
  interrupt: any;
  stop: () => void;
  values?: any;
  userId: string; // 添加userId
};

// 创建StreamContext
const StreamContext = createContext<StreamContextType | undefined>(undefined);

const StreamSession = ({
  children,
  apiKey,
  apiUrl,
  assistantId,
  userId,
}: {
  children: ReactNode;
  apiKey: string | null;
  apiUrl: string;
  assistantId: string;
  userId: string; // 添加userId参数
}) => {
  const [threadId, setThreadId] = useQueryState("threadId");
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 发送消息到自定义API
  const sendMessage = async (content: string) => {
    if (isLoading) return;

    setIsLoading(true);
    setError(null);

    const userMessage: ChatMessage = {
      role: "user",
      content,
      id: Date.now().toString(),
      type: "human",
    };
    setMessages((prev) => [...prev, userMessage]);

    try {
      const response = await fetch(`${apiUrl}/chat/completions`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...(apiKey && { Authorization: `Bearer ${apiKey}` }),
        },
        body: JSON.stringify({
          messages: [...messages, userMessage],
          stream: false,
        }),
      });

      if (!response.ok) {
        throw new Error(`API request failed: ${response.statusText}`);
      }

      const data = await response.json();
      const assistantMessage: ChatMessage = {
        role: "assistant",
        content: data.choices?.[0]?.message?.content || "No response",
        id: Date.now().toString(),
        type: "ai",
      };

      setMessages((prev) => [...prev, assistantMessage]);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to send message");
      // 移除用户消息如果发送失败
      setMessages((prev) => prev.slice(0, -1));
    } finally {
      setIsLoading(false);
    }
  };

  const clearMessages = () => {
    setMessages([]);
    setError(null);
  };

  // Submit方法用于处理中断响应
  const submit = async (input: any, config?: any) => {
    try {
      // 这里可以根据实际需要实现submit逻辑
      console.log("Submit called with:", input, config);
      // 暂时实现为空，可以根据实际API需求进行扩展
    } catch (err) {
      console.error("Submit failed:", err);
    }
  };

  // 获取消息元数据
  const getMessagesMetadata = (message: any) => {
    // 暂时返回空对象，可以根据实际需求扩展
    return {};
  };

  // 设置分支
  const setBranch = (branch: any) => {
    // 暂时实现为空，可以根据实际需求扩展
    console.log("setBranch called with:", branch);
  };

  // 停止方法
  const stop = () => {
    // 暂时实现为空，可以根据实际需求扩展
    console.log("stop called");
  };

  // 检查API状态
  const checkApiStatus = async (
    apiUrl: string,
    apiKey: string | null,
  ): Promise<boolean> => {
    try {
      const response = await fetch(`${apiUrl}/health`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          ...(apiKey && { Authorization: `Bearer ${apiKey}` }),
        },
      });
      return response.ok;
    } catch (error) {
      console.error("API status check failed:", error);
      return false;
    }
  };

  useEffect(() => {
    checkApiStatus(apiUrl, apiKey).then((ok) => {
      if (!ok) {
        toast.error("Failed to connect to API server", {
          description: () => (
            <p>
              Please ensure your API server is running at <code>{apiUrl}</code>{" "}
              and your API key is correctly set (if required).
            </p>
          ),
          duration: 10000,
          richColors: true,
          closeButton: true,
        });
      }
    });
  }, [apiKey, apiUrl]);

  const streamValue: StreamContextType = {
    messages,
    isLoading,
    error,
    sendMessage,
    clearMessages,
    threadId,
    setThreadId,
    submit: async () => {}, // placeholder
    getMessagesMetadata: () => null, // placeholder
    setBranch: () => {}, // placeholder
    interrupt: null,
    stop: () => {},
    values: undefined,
    userId, // 添加userId到context
  };

  return (
    <StreamContext.Provider value={streamValue}>
      {children}
    </StreamContext.Provider>
  );
};

// Default values for the form
const DEFAULT_API_URL = "http://localhost:8013";
const DEFAULT_ASSISTANT_ID = "agent";
const DEFAULT_USER_ID = "test_user";

export const StreamProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  // 获取认证信息
  const { isAuthenticated, user, isLoading: authLoading } = useAuth();

  // Get environment variables
  const envApiUrl: string | undefined = process.env.NEXT_PUBLIC_API_URL;
  const envAssistantId: string | undefined =
    process.env.NEXT_PUBLIC_ASSISTANT_ID;
  const envUserId: string | undefined = process.env.NEXT_PUBLIC_USER_ID;

  // Use URL params with env var fallbacks
  // API URL获取优先级：URL参数 > 环境变量 > 默认值
  const [apiUrl, setApiUrl] = useQueryState("apiUrl", {
    defaultValue: envApiUrl || DEFAULT_API_URL,
  });

  // Assistant ID获取优先级：URL参数 > 环境变量 > 空字符串
  const [assistantId, setAssistantId] = useQueryState("assistantId", {
    defaultValue: envAssistantId || "",
  });

  // User ID获取优先级：URL参数 > 环境变量 > 默认值
  const [userId, setUserId] = useQueryState("userId", {
    defaultValue: envUserId || DEFAULT_USER_ID,
  });

  // For API key, use localStorage with env var fallback
  const [apiKey, _setApiKey] = useState(() => {
    const storedKey = getApiKey();
    return storedKey || "";
  });

  const setApiKey = (key: string) => {
    window.localStorage.setItem("lg:chat:apiKey", key);
    _setApiKey(key);
  };

  // Determine final values to use, prioritizing login user > URL params > env vars
  const finalApiUrl = apiUrl || envApiUrl;
  const finalAssistantId = assistantId || envAssistantId;
  // 优先使用登录用户的userId，然后是URL参数，最后是环境变量和默认值
  const finalUserId =
    isAuthenticated && user?.userId
      ? user.userId
      : userId || envUserId || DEFAULT_USER_ID;

  // 如果正在加载认证状态，显示加载界面
  if (authLoading) {
    return (
      <div className="flex h-screen w-full items-center justify-center">
        <div className="text-center">
          <div className="mb-4">
            <LangGraphLogoSVG className="mx-auto h-12 w-12" />
          </div>
          <p className="text-muted-foreground">正在验证登录状态...</p>
        </div>
      </div>
    );
  }

  // Show the form if we: don't have an API URL, or don't have an assistant ID
  if (!finalApiUrl || !finalAssistantId) {
    return (
      <div className="flex min-h-screen w-full items-center justify-center p-4">
        <div className="animate-in fade-in-0 zoom-in-95 bg-background flex max-w-3xl flex-col rounded-lg border shadow-lg">
          <div className="mt-14 flex flex-col gap-2 border-b p-6">
            <div className="flex flex-col items-start gap-2">
              <LangGraphLogoSVG className="h-7" />
              <h1 className="text-xl font-semibold tracking-tight">
                Agent Chat
              </h1>
            </div>
            <p className="text-muted-foreground">
              Welcome to Agent Chat! Before you get started, you need to enter
              the URL of the API deployment and the assistant ID.
            </p>
            {/* 显示当前登录状态和userId */}
            <div className="text-muted-foreground mt-2 text-sm">
              <p>登录状态: {isAuthenticated ? "已登录" : "未登录"}</p>
              <p>当前用户ID: {finalUserId}</p>
              {isAuthenticated && user && <p>登录用户: {user.username}</p>}
            </div>
          </div>
          <form
            onSubmit={(e) => {
              e.preventDefault();

              const form = e.target as HTMLFormElement;
              const formData = new FormData(form);
              const apiUrl = formData.get("apiUrl") as string;
              const assistantId = formData.get("assistantId") as string;
              const userId = formData.get("userId") as string;
              const apiKey = formData.get("apiKey") as string;

              setApiUrl(apiUrl);
              setApiKey(apiKey);
              setAssistantId(assistantId);
              setUserId(userId);

              form.reset();
            }}
            className="bg-muted/50 flex flex-col gap-6 p-6"
          >
            <div className="flex flex-col gap-2">
              <Label htmlFor="apiUrl">
                API URL<span className="text-rose-500">*</span>
              </Label>
              <p className="text-muted-foreground text-sm">
                This is the URL of your custom API deployment. Can be a local,
                or production deployment.
              </p>
              <Input
                id="apiUrl"
                name="apiUrl"
                className="bg-background"
                defaultValue={apiUrl || DEFAULT_API_URL}
                required
              />
            </div>

            <div className="flex flex-col gap-2">
              <Label htmlFor="assistantId">
                Assistant ID<span className="text-rose-500">*</span>
              </Label>
              <p className="text-muted-foreground text-sm">
                This is the ID of the assistant to use when making API requests.
              </p>
              <Input
                id="assistantId"
                name="assistantId"
                className="bg-background"
                defaultValue={assistantId || DEFAULT_ASSISTANT_ID}
                required
              />
            </div>

            <div className="flex flex-col gap-2">
              <Label htmlFor="userId">
                User ID<span className="text-rose-500">*</span>
              </Label>
              <p className="text-muted-foreground text-sm">
                This is the ID of the user for tracking conversations and
                history.
              </p>
              <Input
                id="userId"
                name="userId"
                className="bg-background"
                defaultValue={userId || DEFAULT_USER_ID}
                required
              />
            </div>

            <div className="flex flex-col gap-2">
              <Label htmlFor="apiKey">API Key</Label>
              <p className="text-muted-foreground text-sm">
                This is <strong>NOT</strong> required if using a local API
                server. This value is stored in your browser's local storage and
                is only used to authenticate requests sent to your API server.
              </p>
              <PasswordInput
                id="apiKey"
                name="apiKey"
                defaultValue={apiKey ?? ""}
                className="bg-background"
                placeholder="your-api-key..."
              />
            </div>

            <div className="mt-2 flex justify-end">
              <Button
                type="submit"
                size="lg"
              >
                Continue
                <ArrowRight className="size-5" />
              </Button>
            </div>
          </form>
        </div>
      </div>
    );
  }

  // 如果正在加载认证状态，显示加载界面
  if (authLoading) {
    return (
      <div className="flex h-screen w-full items-center justify-center">
        <div className="text-center">
          <div className="mb-4">
            <LangGraphLogoSVG className="mx-auto h-12 w-12" />
          </div>
          <p className="text-muted-foreground">正在验证登录状态...</p>
        </div>
      </div>
    );
  }

  // 如果未登录，显示登录提示
  if (!isAuthenticated) {
    return (
      <div className="flex h-screen w-full items-center justify-center">
        <div className="text-center">
          <div className="mb-4">
            <LangGraphLogoSVG className="mx-auto h-12 w-12" />
          </div>
          <p className="text-muted-foreground mb-4">请先登录以使用应用</p>
          <p className="text-muted-foreground text-sm">
            当前用户ID: {finalUserId}
          </p>
        </div>
      </div>
    );
  }

  return (
    <StreamSession
      apiKey={apiKey}
      apiUrl={apiUrl}
      assistantId={assistantId}
      userId={finalUserId}
    >
      {children}
    </StreamSession>
  );
};

// Create a custom hook to use the context
export const useStreamContext = (): StreamContextType => {
  const context = useContext(StreamContext);
  if (context === undefined) {
    throw new Error("useStreamContext must be used within a StreamProvider");
  }
  return context;
};

export default StreamContext;
